var app = getApp();
var util = require('../../../utils/util.js');
var caigouPage;  //存放上一个页面的信息
Page({
  /**
   * 页面的初始数据
   */
  data: {
    nArr_index:-1,
    shop_ids: [],
    buttonClicked: false,  //防止重复点击
    isOrderremark:false,  //订单备注
    issuper:false,  //选择供应商
    load_num:1
  },
  // 提交订单或需求单
  submit_but(e) {
    var that = this;
    if(that.data.load_num==0){
      that.setData({
        buttonClicked: true     //防止重复点击
      });
    }else if(that.data.load_num==1){
      return;
    }; 
    var nArr = that.data.nArr;
    if(that.data.good_dir_set==2 && that.data.client_is_store==0 && that.data.purchase_type==1 && that.data.is_zi_cai==0){  //模式5+非自采
      var supplier_count_list=that.data.supplier_count_list;
      var have_super= supplier_count_list.every((val) => val.id>0);   //必须所有条件都满足返回true
      if(!have_super){
        wx.showModal({
          content:'请给没有供应商的菜品选择供应商',
          showCancel: false,
              confirmText:"我知道了",
              success: function (res) {}
        }); 
        return;
      };
    };
    // if((that.data.client_is_store<0 && that.data.type_level==1 || that.data.client_is_store ==1) && that.data.price_type!=3){   //向审核人发消息（需求单，且非询价单）
    //   valid='client_order_check';
    // }else 
    var shop_ids = (e.currentTarget.dataset.shop).split(',');  
      var inter_name;
      if(that.data.good_dir_set==3 || that.data.good_dir_set==2 && that.data.client_is_store==1 || that.data.client_is_store<0 && that.data.type_level==1){  //模式1，4，6+非企业独立版(下需求单)
        inter_name='api/Order/SubmitOrder';
      }else{  //其他(下订单)   
        inter_name='api/Order/SubmitOrderMany';    
      };
      wx.request({
        url: app.globalData.url + inter_name, 
        method: "POST",
        data: {
          openid: app.globalData.openid,
          shop_ids: shop_ids,
          merge_ids: [],
          order_remark:nArr,
          set_songhuo_time:that.data.nSongArr,
          is_ku:that.data.is_ku
        },
        success: function (res) {
          if (res.data.status == 1) {
            wx.showToast({
              title: res.data.msg,
              mask:true,
              icon: 'success',
              duration:500,
              success: function () {         
                app.globalData.dingdan_show = 1;              
                app.globalData.toneed_order=1; //导航在新订单/新需求单
                var orders_ids=res.data.data;
                that.updatelink(orders_ids,orders_ids[0].id,orders_ids[0].supplier_id,orders_ids.length,orders_ids.length)
                wx.switchTab({
                  url: '../../dingdan/dingdan'
                }); 
              }
            })
          } else {
            wx.showToast({
              title: '订单提交失败',
            })
          }
        }
      });
  },
  // 订单关联
  updatelink(orders_ids,id,supplier_id,change_len,len){
    var that = this;
    app.AppHttp('api/Orders/updateOrderDetailLink', {  //订单详情关联
      id:id,
      supplier_id:supplier_id
    }, function (res) {
      app.UpAsso('java_order/update_order_allow_batch/'+id, //订单关联
      function (ress) {
        if(change_len){
          change_len--;
          if(change_len>0){
            that.updatelink(orders_ids,orders_ids[len-change_len].id,orders_ids[len-change_len].supplier_id,change_len,len);     
          };
        };
      });
    });
  },
  open_order_remark(e){
    var index=e.currentTarget.dataset.index;
    this.setData({
      isOrderremark:true,
      nArr_index:index,
      order_remark:this.data.nArr[index]?this.data.nArr[index]:""
    });
  },
  confirmNOkClick(){
    this.setData({
      isOrderremark:false
    });
  },
  beizhuinput(e){
    this.setData({
      order_remark:e.detail.value
    });
  },
  confirmOkClick:function(){
    var nArr=this.data.nArr;
    nArr[this.data.nArr_index]=this.data.order_remark;
    this.setData({
      isOrderremark:false,
      nArr:nArr
    });
  },
  /**
   * 选择时间
   */
  bindDateChange(e){
    var nSongArr=this.data.nSongArr;
    let nSong_index = e.currentTarget.dataset.index
    nSongArr[nSong_index] = e.detail.value;
    this.setData({
      nSongArr:nSongArr
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(e) {
    var shop_ids = (e.shop_ids).split(',');
    var that = this;
    var cur_time = util.formatTime(new Date());
    var tomorrow_day = util.formatTime(new Date(Date.parse(new Date(cur_time))+3600000 * 24));
    tomorrow_day = tomorrow_day.substring(0,10);
    that.setData({
      is_zi_cai:app.globalData.loginInfo.is_zi_cai,  //是否自采
      good_dir_set:app.globalData.loginInfo.good_dir_set,    //目录类型
      client_is_store:app.globalData.loginInfo.client_is_store,  //<0未加入集团，==0加入集团无库 ,==1加入集团有库
      purchase_type:app.globalData.loginInfo.purchase_type,   //1门店采购，2总部采购
      price_type:e.price_type,   //客户定价模式
      type:e.type,
      is_ku:e.is_ku,
      raplace_h:0.8*wx.getSystemInfoSync().windowHeight,
      type_level:app.globalData.type_level,
      cur_time:cur_time,
      tomorrow_day:tomorrow_day
    });
    console.log(this.data.tomorrow_day);
    app.AppHttp('api/Client/KitchenManage', {  //判断审核权限开关
      id: app.globalData.loginInfo.id
    }, function (res) {
      that.setData({
        check_open_close: res.data.ClientFind.check_open_close
      });
    });
    if(e.type=='shopcar'){
      that.car_Preview(shop_ids);
    }else if(e.type=='caigou'){
      const pages = getCurrentPages();    //获取当前页面信息栈
      caigouPage = pages[pages.length - 2]; //获取上一个页面信息 
      var pr_num_str = (e.pr_num_str).split(',');
      var shop_ids= JSON.parse(shop_ids);
      var id_str=shop_ids.join(',');
      that.setData({
        pr_num_str:pr_num_str,
        order_ids:e.order_ids,
        id_str:id_str,
        shop_ids:shop_ids,
        is_enquiry:e.is_enquiry
      });
      that.caigou_Preview();
    }; 
  },
  // 购物车预览
  car_Preview:function(shop_ids){
    var that = this;
    wx.request({
      url: app.globalData.url + 'api/Order/orderPreview',
      method: "POST",
      data: {
        openid: app.globalData.openid,
        shop_ids: shop_ids
      },
      success: function (res) {
        that.setData({
          load_num:0,
          nArr:Array(res.data.supplier_count_list.length).fill(''),  //初始(每一项为'')数组
          nSongArr:Array(res.data.supplier_count_list.length).fill(''),
          loginInfo: res.data,
          supplier_count_list:res.data.supplier_count_list,
          shop_ids: shop_ids
        });
      }
    });
  },
  // 采购预览
  caigou_Preview:function(){
    var that = this;
    app.AppHttp('api/Order/purchasePreview', {
      openid: app.globalData.openid,
      id_str:that.data.id_str
    }, function (res) {
      that.setData({
        load_num:0,
        nArr:Array(res.data.supplier_count_list.length).fill(''),  //初始(每一项为'')数组,
        nSongArr:Array(res.data.supplier_count_list.length).fill(''),
        loginInfo: res.data,
        supplier_count_list:res.data.supplier_count_list
      })  
    });
  },
  // 选择供应商
  chose_super:function(e){
    util.showBuyModal(this);  
    var that = this;
    that.setData({
      issuper:true,
      supplier_shop_ids:e.currentTarget.dataset.supplier_shop_ids,
      check_super_id:e.currentTarget.dataset.id,
      chose_sur_index:e.currentTarget.dataset.index,
    });
    if(that.data.good_dir_set<1){   //非企业版
      app.AppHttp('api/Client/SupplierList', {
        openid: app.globalData.openid,
        type: 1
      }, function (res) {
        if(res.data.status==-1){
          wx.showLoading({
            title: res.data.msg,
            duration:500
          });
          return;
        }
        var super_list=res.data.data[0]
        super_list = super_list.filter(function (item) {
          return (item.status==1 && item.is_zicai_supplier==0); //筛选正常且非自采的合作用户
        });
        that.setData({
          super_list:super_list
        });
      });
    }else if(that.data.good_dir_set>=1){  //企业版
      app.AppHttp('api/Client/belongBusinessSupplier', {
        client_id:app.globalData.loginInfo.id
      }, function (res) {
        if(res.data.status==-1){
          wx.showLoading({
            title: res.data.msg,
            duration:500
          });
          return;
        }
        that.setData({
          super_list: res.data
        });
      }); 
    }
  },
  // 关闭供应商弹窗
  close_super:function(){
    util.hideBuyModal(this,"issuper");
  },
  // 确定供应商
  super_conf:function(e){
    var that = this;
    var b_supplier_id=e.currentTarget.dataset.supplier_id;
    if(this.data.type=='shopcar'){
      app.AppHttp('api/Shopping/changeShoppingBelong', {
        supplier_shop_ids:that.data.supplier_shop_ids,
        b_supplier_id:b_supplier_id
      }, function (res) {
        that.car_Preview(that.data.shop_ids);
      });
    }else if(this.data.type=='caigou'){
      app.AppHttp('api/Order/changeShoppingBelong', {
        supplier_detail_ids:that.data.supplier_shop_ids,
        b_supplier_id:b_supplier_id
      }, function (res) {
        that.caigou_Preview();
        caigouPage.PurchasingList();
      });
    }   
    util.hideBuyModal(this,"issuper");
  },
  // 采购单生成
  cai_submit_but:function(){
    var that = this;  
    if(that.data.load_num==0){
      that.setData({
        buttonClicked: true     //防止重复点击
      });
    }else if(that.data.load_num==1){
      return;
    }; 
    var supplier_count_list=that.data.supplier_count_list;
    var have_super= supplier_count_list.every((val) => val.id>0);   //必须所有条件都满足返回true
    if(!have_super){
      wx.showModal({
        content:'请给没有供应商的菜品选择供应商',
        showCancel: false,
            confirmText:"我知道了",
            success: function (res) {
              that.setData({
                buttonClicked:false     //防止重复点击
              });
            }
      }); 
      return;
    };
    if(that.data.good_dir_set==2 && that.data.client_is_store==1 && that.data.purchase_type==2){  //模式6
      app.AppHttp('api/Order/needCreatePurchase', {
        openid: app.globalData.openid,
        ids:that.data.shop_ids,
        order_ids:that.data.order_ids,
        pr_num_str:that.data.pr_num_str,
        order_remark:that.data.nArr
      }, function (res) { 
        wx.showToast({
          title:res.data.msg
        });
        wx.navigateBack({
          delta: 1
        });
      });
    }else{
      app.AppHttp('api/Order/createOrderByPurchaseMany', {
        openid: app.globalData.openid,
        detail_id_arr:that.data.shop_ids,
        order_remark:that.data.nArr,
        is_enquiry:that.data.is_enquiry
      }, function (res) {
        app.globalData.caigou_shua=1;   
        wx.request({
          url: app.globalData.url + 'api/Message1/valid',
          method: 'GET',
          data: {
            id: res.data.data,
            message_type:"client_order_check"
          },
          success: function (res) {}
        });
        wx.switchTab({
          url: '/pages/caigou/caigou'
        })
      }); 
    } 
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
      
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  }
})